package com.ytktt.study.week7.task6.seq.repository;

import com.ytktt.study.week7.task6.seq.entity.SequenceInfoEntity;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 订单信息仓库
 *
 * @author ytk
 */
@Slf4j
public class SequenceInfoRepository {

    private SequenceInfoRepository() {}

    private static class StudyRepositoryHolder {
        private static final SequenceInfoRepository HOLDER = new SequenceInfoRepository();
    }

    public static final SequenceInfoRepository getInstance() {
        return StudyRepositoryHolder.HOLDER;
    }

    public long genId(String name, Connection connection) throws SQLException {
        SequenceInfoEntity studyEntity = null;
        String querySql = "SELECT name, current_value AS currentValue, step FROM tb_sequence_info WHERE name = ? FOR UPDATE";
        try (PreparedStatement preparedStatement = connection.prepareStatement(querySql)) {
            preparedStatement.setString(1, name);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    studyEntity = new SequenceInfoEntity();
                    studyEntity.setName(resultSet.getString("name"));
                    studyEntity.setCurrentValue(resultSet.getLong("currentValue"));
                    studyEntity.setStep(resultSet.getInt("step"));
                }
            }
        }
        long seq = 0L;
        if (null != studyEntity) {
            seq = studyEntity.getCurrentValue();
            long newValue = seq + studyEntity.getStep();
            String updateSql = "UPDATE tb_sequence_info SET current_value = ? where name = ?";
            try (PreparedStatement preparedStatement = connection.prepareStatement(updateSql)) {
                preparedStatement.setLong(1, newValue);
                preparedStatement.setString(2, name);
                preparedStatement.executeUpdate();
            }
        }
        return seq;
    }

}
